const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const excelService = require('../services/excelService');

const router = express.Router();

// 配置文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = './uploads/temp';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'import-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    if (ext !== '.xlsx' && ext !== '.xls') {
      return cb(new Error('只支持Excel文件(.xlsx, .xls)'));
    }
    cb(null, true);
  },
  limits: {
    fileSize: 10 * 1024 * 1024 // 10MB
  }
});

/**
 * POST /api/import/excel
 * 导入Excel文件
 */
router.post('/excel', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '请上传Excel文件'
      });
    }

    console.log('收到Excel导入请求:', req.file.originalname);

    // 导入Excel
    const result = await excelService.importExcel(req.file.path);

    // 删除临时文件
    fs.unlinkSync(req.file.path);

    res.json(result);
  } catch (error) {
    console.error('导入失败:', error.message);
    
    // 删除临时文件
    if (req.file && fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path);
    }

    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * GET /api/import/template
 * 下载Excel模板
 */
router.get('/template', (req, res) => {
  const templatePath = path.join(__dirname, '../../templates/personnel_template.xlsx');
  
  if (fs.existsSync(templatePath)) {
    res.download(templatePath, '人员信息导入模板.xlsx');
  } else {
    res.status(404).json({
      success: false,
      message: '模板文件不存在'
    });
  }
});

module.exports = router;


